﻿#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable : 6031)
#include "sl.h"

void print(sl* p)
{
	int i = 0;
	for (i = 0; i < p->sz; i++)
	{
		printf("%d ", p->p[i]);
	}
}

void initsl(sl* p)
{
	int* pc = (int*)malloc(sizeof(sl) * 3);
	if (!pc)
	{
		perror("malloc");
		return;
	}
	p->p = pc;
	p->num = 3;
	p->sz = 0;
}

void checksl(sl* p)
{
	if (p->sz == p->num)
	{
		int* pc = (int*)realloc(p->p, sizeof(sl) * (p->num) * 2);
		if (!pc)
		{
			perror("realloc");
			return;
		}
		p->p = pc;
		p->num += 3;
	}
}

void pushback(sl* p, int x)
{
	checksl(p);
	p->p[p->sz] = x;
	p->sz++;
}

void freesl(sl* p)
{
	free(p->p);
	p->num = 0;
	p->sz = 0;
	p->p = NULL;
}

void pushfront(sl* p, int x)
{
	checksl(p);
	/*int i = 0;
	int end = p->sz-1;
	while (end >= 0)
	{
		p->p[end+1] = p->p[end];
		end--;
	}
	p->p[0] = x;
	p->sz++;*/
	pushmid(p, 1, x);
}

void popback(sl* p)
{
	assert(p->sz > 0);
	p->sz--;
}

void popfront(sl* p)
{
	assert(p->sz > 0);
	/*int i = 0;
	for (i = 0; i < p->sz - 1; i++)
	{
		p->p[i] = p->p[i + 1];
	}
	p->sz--;*/
	erasemid(p, 1);
}

void pushmid(sl* p, int pos, int x)
{
	assert(pos > 0 && pos <= p->sz);
	checksl(p);
	int end = p->sz - 1;
	while (pos-1 <= end)
	{
		p->p[end + 1] = p->p[end];
		end--;
	}
	p->p[pos - 1] = x;
	p->sz++;
}

void erasemid(sl* p, int pos)
{
	assert(pos > 0 && pos <= p->sz);
	int str = pos - 1;
	while (str < p->sz - 1)
	{
		p->p[str] = p->p[str + 1];
		str++;
	}
	p->sz--;
}